import * as Path from "path";

export function createId() {
    return `_${Date.now()}`
}

export function getProperty<Entity>(entities: Entity[], propertyName = 'id') {
    const ids = entities.map(value => value[propertyName]);
    return [...new Set(ids)];
}

export function setProperty<Entity, DbEntity>(
    entities: Entity[],
    dbEntities: DbEntity[],
    match: (dbEntity: DbEntity, entity: Entity) => boolean,
    set: (dbEntity: DbEntity, entity: Entity) => any,
    notFoundProcess?: (entity: Entity) => void,
    moreMatchAndSet?: {
        match: (dbEntity: DbEntity, entity: Entity) => boolean,
        set: (dbEntity: DbEntity, entity: Entity) => any,
    }[]
) {
    function process(entity, index, match, set) {
        const dbEntity = dbEntities.find(dbEntity => match(dbEntity, entity));
        if (dbEntity) {
            const r = set(dbEntity, entity);
            if (r) {
                entities[index] = r;
            }
        } else if (notFoundProcess) {
            notFoundProcess(entity);
        }
    }

    for (let index in entities) {
        let entity = entities[index];
        process(entity, index, match, set);
        if (moreMatchAndSet.length > 0) {
            for (let {match, set} of moreMatchAndSet) {
                process(entity, index, match, set)
            }
        }
    }
}

export function getLack(arr = [], newArr = []) {
    return arr.filter(value => newArr.indexOf(value) === -1);
}

export function pathJoin(...paths: string[]) {
    return Path.join(...paths).replace(/\\/g, '/');
}